package com.lizard.schedule.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.android.volley.VolleyError;
import com.lizard.schedule.R;
import com.lizard.schedule.ScheduleApplication;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.manager.observer.ObserverIfaces.Logout;
import com.lizard.schedule.manager.observer.ObserverManager;
import com.lizard.schedule.manager.umeng.UmengManager;
import com.lizard.schedule.manager.umeng.UmengShareManager;
import com.lizard.schedule.net.http.consts.AppType;
import com.lizard.schedule.net.http.consts.ReturnCode;
import com.lizard.schedule.net.http.request.HttpRequestManager;
import com.lizard.schedule.net.http.request.HttpResponseListener;
import com.lizard.schedule.net.http.request.bean.VersionRequest;
import com.lizard.schedule.net.http.response.bean.VersionResponse;
import com.lizard.schedule.persistence.sharedpreferences.CommonPref;
import com.lizard.schedule.service.UpgradeService;
import com.lizard.schedule.ui.activity.base.BaseFragmentAcitivity;
import com.lizard.schedule.ui.fragment.LeftDrawerFragment;
import com.lizard.schedule.ui.fragment.MyScheduleFragment;
import com.lizard.schedule.ui.view.Titlebar;
import com.lizard.schedule.utils.ScheduleUtil;
import com.lizard.schedule.utils.StatusBarUtil;
import com.lizard.schedule.utils.TimeUtil;
import com.lizard.schedule.utils.ToastUtil;
import com.lizard.schedule.widget.ScheduleAlertDialog;
import com.lizard.schedule.widget.ScheduleToast;
import com.umeng.socialize.utils.Log;

/**
 * 首页
 */
public class MainPageActivity extends BaseFragmentAcitivity implements DrawerLayout.DrawerListener, Logout {

    /**
     * 需要验证账户(如果是登录用户)
     */
    public static final String PARAM_VERIFY_ACCOUNT = "verify_account";

    /**
     * 抽屉式布局
     */
    private DrawerLayout mDrawerLayout;
    /**
     * 左侧抽屉
     */
    private View mLeftDrawer;
    /**
     * 记录最后一次按返回键的时间，用于双击返回键退出功能
     */
    private long mLastBackPressTime;
    /**
     * 顶部栏
     */
    private Titlebar mTitlebar;
    /**
     * 侧边栏当前状态
     */
    private int mDrawerState = DrawerLayout.STATE_IDLE;
    /**
     * 主内容fragment
     */
    private MyScheduleFragment myScheduleFragment;
    /**
     * 左侧抽屉内容fragment
     */
    private LeftDrawerFragment mLeftDrawerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 内存回收之后重启
        if (savedInstanceState != null) {
            Intent intent = new Intent(ScheduleApplication.applicationContext, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ScheduleApplication.applicationContext.startActivity(intent);
            UmengManager.getInstance().onKillProcess(this);
            finish();
            android.os.Process.killProcess(android.os.Process.myPid());
            return;
        }

        setContentView(R.layout.a_main_page);

        // 设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, R.color.schedule_blue);

        initView();
        setViewClick();

        if (!TextUtils.isEmpty(AccountManager.getInstance().getUsername())
                && getIntent().getBooleanExtra(PARAM_VERIFY_ACCOUNT, false)) {
            verifyAccount();    // 默默验证账户
        }

        registObservers();

        // 检查新版本
        checkVersion();

    }

    /**
     * 注册观察者通知
     */
    private void registObservers() {
        ObserverManager.getInstance().registerLogout(this);
    }

    /**
     * 注销观察者通知
     */
    private void unregistObservers() {
        ObserverManager.getInstance().unregisterLogout(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * view初始化
     */
    private void initView() {
        mTitlebar = (Titlebar) findViewById(R.id.title_bar);
        mLeftDrawer = findViewById(R.id.left_drawer);
        initDrawerLayout();
        initContentFrame();
        initLeftDrawerFrame();
    }

    /**
     * 抽屉式布局主内容初始化
     */
    private void initContentFrame() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.content_frame);
        if (fragment != null && fragment instanceof MyScheduleFragment) { // 存在(内存被回收后进来)
            myScheduleFragment = (MyScheduleFragment) fragment;
            return;
        }
        myScheduleFragment = new MyScheduleFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.content_frame, myScheduleFragment).commitAllowingStateLoss();
    }

    /**
     * 抽屉式布局抽屉内容初始化
     */
    private void initLeftDrawerFrame() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.left_drawer);
        if (fragment != null && fragment instanceof LeftDrawerFragment) { // 存在(内存被回收后进来)
            return;
        }
        mLeftDrawerFragment = new LeftDrawerFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.left_drawer, mLeftDrawerFragment).commitAllowingStateLoss();
    }

    /**
     * 初始化抽屉式布局
     */
    private void initDrawerLayout() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerListener(this);
    }

    /**
     * view的点击事件设置
     */
    private void setViewClick() {
        setMenuBtnClk();
        setAddBtnClk();
        mTitlebar.setOnDoubleClickListener(new Titlebar.OnDoubleClickListener() {
            @Override
            public void onDobuleClick() {
                myScheduleFragment.scrollToTop();
            }
        });
    }

    /**
     * 设置菜单按钮点击事件
     */
    private void setMenuBtnClk() {
        mTitlebar.setLeftBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                menuToggle();
            }
        });
    }

    /**
     * 设置添加按钮点击事件
     */
    private void setAddBtnClk() {

        mTitlebar.setRightBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeLeftDrawer();
                myScheduleFragment.createNewSchedule();
            }
        });
    }

    /**
     * 菜单开关
     */
    private void menuToggle() {
        if (mDrawerLayout.isDrawerOpen(mLeftDrawer)) {
            closeLeftDrawer();
        } else {
            openLeftDrawer();
        }
    }

    /**
     * 关闭左侧抽屉
     */
    public void closeLeftDrawer() {
        mDrawerLayout.closeDrawer(mLeftDrawer);
        mTitlebar.setLeftBtnSelected(false);
    }

    /**
     * 打开左侧抽屉
     */
    private void openLeftDrawer() {
        mDrawerLayout.openDrawer(mLeftDrawer);
        mTitlebar.setLeftBtnSelected(true);
    }

    /**
     * 判断左侧抽屉是否打开
     *
     * @return
     */
    private boolean isLeftDrawerOpen() {
        return mDrawerLayout.isDrawerOpen(mLeftDrawer);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU: // 设备菜单键
                menuToggle();
                return true;
            case KeyEvent.KEYCODE_BACK: // 设备返回键
                backPress();
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 返回键盘操作
     */
    private void backPress() {

        if (isLeftDrawerOpen() || mDrawerState == DrawerLayout.STATE_SETTLING) {
            closeLeftDrawer();
            return;
        }

        long now = System.currentTimeMillis();
        if (Math.abs(now - mLastBackPressTime) < 4000) {
            ScheduleToast.cancelAll();
            finish();   // 双击返回键退出程序只是关闭当前首页 进程还在
        } else {
            mLastBackPressTime = now;
            ToastUtil.showScheduleToastS(R.string.back_press_dbl_hint);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        finish();
        startActivity(intent);
    }

    /**
     * 侧边栏滑动中
     *
     * @param view
     * @param v
     */
    @Override
    public void onDrawerSlide(View view, float v) {
        if (v == 0) {
            mTitlebar.setLeftBtnSelected(false);
        } else if (v == 1) {
            mTitlebar.setLeftBtnSelected(true);
        }
    }

    /**
     * 侧边栏展开
     *
     * @param view
     */
    @Override
    public void onDrawerOpened(View view) {
        mTitlebar.setLeftBtnSelected(true);

        // 每次展开的时候通知界面重新加载未结束的历史计划数
        ObserverManager.getInstance().notifyReloadUnfinishedHistoryScheduleCounts();
    }

    /**
     * 侧边栏关闭
     *
     * @param view
     */
    @Override
    public void onDrawerClosed(View view) {
        mTitlebar.setLeftBtnSelected(false);
    }

    /**
     * 侧边栏状态改变
     *
     * @param i
     */
    @Override
    public void onDrawerStateChanged(int i) {
        mDrawerState = i;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregistObservers();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UmengShareManager.getInstance().sinaSsoCallBack(requestCode, resultCode, data);
    }

    /**
     * 对免登录的账户默默验证
     */
    private void verifyAccount() {
        if(AccountManager.getInstance().getThirdLoginType() > 0){
            AccountManager.getInstance().verifyAccountThird(null);
        } else{
            AccountManager.getInstance().verifyAccount(null);
        }
    }

    /**
     * 收到退出登录通知
     */
    @Override
    public void logout() {
        mLeftDrawerFragment.logOut(false);
    }

    /**
     * 检查新版本
     */
    private void checkVersion() {
        // 访问server获取最新版本信息
        VersionRequest request = new VersionRequest();
        HttpRequestManager.getInstance().request(request, new HttpResponseListener<VersionResponse>() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                // do nothing
            }

            @Override
            public void onResponse(VersionResponse response) {
                if (ReturnCode.SUCCESS.equals(response.getReturnCode())) {
                    int lastVersionCode = response.getVersion();
                    String lastVersionName = response.getVersionName();
                    String versionInfo = response.getVersionInfo();
                    String appType = response.getAppType();
                    final String versionLink = response.getVersionLink();

                    if (!AppType.ANDROID.equals(appType)) {
                        return;
                    }

                    if (lastVersionCode > ScheduleUtil.getVersionCode()) { // 有新版本
                        alertUpdateNewVersion(lastVersionName, lastVersionCode, versionLink);
                    }

                }
            }
        });
    }

    /**
     * 提示用户并更新新版本
     *
     * @param newVersionName
     * @param newVersionCode
     * @param url
     */
    private void alertUpdateNewVersion(String newVersionName, final int newVersionCode, final String url) {

        long lastUpgradeAlertTime = CommonPref.getInstance().getlastUpgradeAlertTime();
        long nowTime = System.currentTimeMillis();

        if (TimeUtil.getDayInterval(lastUpgradeAlertTime, nowTime) != 0) { // 时间间隔一天以上

            CommonPref.getInstance().setLastUpgradeAlertTime(System.currentTimeMillis());

            String updateStringFormat = getString(R.string.new_version_alert_message);
            new ScheduleAlertDialog.Builder(this)
                    .setMessage(String.format(updateStringFormat, newVersionName))
                    .setPositiveButton(R.string.update, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            UpgradeService.start(MainPageActivity.this, url, newVersionCode);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null).show();
        }

    }
}
